package cn.vconinfo.lims.delivery.task;

import cn.vconinfo.base.utils.DateUtil;
import cn.vconinfo.base.utils.StringUtils;
import cn.vconinfo.lims.delivery.entity.*;
import cn.vconinfo.lims.delivery.mapper.GeneralManageMapper;
import cn.vconinfo.lims.delivery.model.*;
import cn.vconinfo.lims.delivery.service.RequestTestItemService;
import cn.vconinfo.lims.delivery.service.TestItemSynchroService;
import cn.vconinfo.lims.delivery.service.XiCangInspectService;
import cn.vconinfo.lims.delivery.utils.GenerateConstant;
import com.alibaba.fastjson.JSON;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.*;

@Component
@RequiredArgsConstructor
@EnableScheduling
public class TestItemSynchroTask {

    private final XiCangInspectService xiCangInspectService;
    private final RequestTestItemService requestTestItemService;
    private final GeneralManageMapper generalManageMapper;

    private final TestItemSynchroService testItemSynchroService;
    private final TestResultXmlExport testResultXmlExport;

    @Value("${lims.hospital}")
    private String hospitalId;

    /**
     *  初始化的方法
     */
    @PostConstruct
    public void synchroInit(){
        // 同步开单项目
        SynchroRequestItem();
        // 同步实验项目
        SynchroSubTestItem();

    }

    /**
     *  同步开单项目
     *
     */
//    @Scheduled(cron = "0 0 11,13 * * ?")
    @Scheduled(cron = "0/10 * * * * ?")
    public void SynchroRequestItem(){
        List<XiCangInspectDelivery> deliveryList = xiCangInspectService.queryXiCangLisItems(null);
        if(!CollectionUtils.isEmpty(deliveryList)){
            List<HospitalProjectLink> insertItemRelateList = new ArrayList<>();
            HospitalProjectLink itemRelate = new HospitalProjectLink();
            itemRelate.setObjectId(StringUtils.stringToLong(hospitalId));
            List<HospitalProjectLink> itemRelateList = requestTestItemService.queryRequestItemRelate(itemRelate);
            HospitalProjectLink relate = null;
            for(XiCangInspectDelivery delivery : deliveryList){
                boolean anyMatch = itemRelateList.parallelStream().anyMatch(predicate -> delivery.getItemCode().equals(predicate.getHospitalDocumentId()));
                if(!anyMatch){
//                    relate = new WRequestitemRelate();
//                    relate.setHospitalId(StringUtils.stringToLong(hospitalId));
//                    relate.setwItemCode(delivery.getItemCode());
//                    relate.setwItemName(delivery.getItemName());
//                    relate.setwShortName(delivery.getShortName());
//                    insertItemRelateList.add(relate);
                    relate = new HospitalProjectLink();
                    relate.setObjectId(StringUtils.stringToLong(hospitalId));
                    relate.setHospitalDocumentId(delivery.getItemCode());
                    relate.setHospitalDocumentName(delivery.getItemName());
                    insertItemRelateList.add(relate);
                }
            }

            if(CollectionUtils.isNotEmpty(insertItemRelateList)){
                requestTestItemService.insertRequestItemBatch(insertItemRelateList);
            }

        }
    }

    /**
     *  同步实验项目
     */
//    @Scheduled(cron = "0 0 12,14 * * ?")
    @Scheduled(cron = "0/10 * * * * ?")
    public void SynchroSubTestItem(){
        XiCangInspectItem inspectItem = new XiCangInspectItem();
        List<XiCangTestSubItem> subItemList = xiCangInspectService.queryXiCangSubItems(inspectItem);
        if(!CollectionUtils.isEmpty(subItemList)){
            List<WTestitemRelate> insertItemRelateList = new ArrayList<>();
            TestSubItemQuery itemRelate = new TestSubItemQuery();
            itemRelate.setHospitalId(StringUtils.stringToLong(hospitalId));
            List<WTestitemRelate> itemRelateList = requestTestItemService.querySubTestItemRelate(itemRelate);
            WTestitemRelate relate = null;
            for(XiCangTestSubItem subItem : subItemList){
                boolean anyMatch = itemRelateList.parallelStream().anyMatch(predicate -> subItem.getSubItemCode().equals(predicate.getSubItemCode()));
                if(!anyMatch){
                    relate = new WTestitemRelate();
                    relate.setHospitalId(StringUtils.stringToLong(hospitalId));
                    relate.setSubItemCode(subItem.getSubItemCode());
                    relate.setSubItemName(subItem.getSubItemName());
                    insertItemRelateList.add(relate);
                }
            }

            if(CollectionUtils.isNotEmpty(insertItemRelateList)){
                requestTestItemService.insertSubTestItemBatch(insertItemRelateList);
            }

        }
    }

    /**
     *  同步检验申请单数据
     *
     */
//    @Scheduled(cron = "0 0/5 8-16 * * ?")
    @Scheduled(cron = "0/10 * * * * ?")
    public void SynchroTestRequestInfo(){
        XiCangRequestQuery query = new XiCangRequestQuery();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        query.setSamplingDateStart(DateUtil.getWeeHourDate(calendar.getTime()));
        query.setSamplingDateEnd(DateUtil.getMidnightDate(calendar.getTime()));
        List<XiCangRequestInfo> requestInfoList = xiCangInspectService.queryXiCangRequestInfo(query);
        if(!CollectionUtils.isEmpty(requestInfoList)){
            WLisRequestQuery info = new WLisRequestQuery();
            info.setHospitalId(StringUtils.stringToLong(hospitalId));
            info.setSamplingDateStart(query.getSamplingDateStart());
            info.setSamplingDateEnd(query.getSamplingDateEnd());
            List<WLisRequestInfo> infoList = requestTestItemService.queryLisRequestInfo(info);
            List<GeneralDTO> sexTypeList = generalManageMapper.getSexType();
            List<GeneralDTO> ageTypeList = generalManageMapper.getAllTypeInfo();
            List<HospitalProjectLink> itemRelateList = getRequestItemInfo();
            WLisRequestInfo lisRequestInfo = null;
            for(XiCangRequestInfo requestInfo : requestInfoList){
                boolean anyMatch = infoList.parallelStream().anyMatch(predicate -> requestInfo.getHospSampleID().equals(predicate.getBarCode()));
                if(!anyMatch){
                    lisRequestInfo = new WLisRequestInfo();
                    lisRequestInfo.setBarCode(requestInfo.getHospSampleID());
                    lisRequestInfo.setHospitalId(StringUtils.stringToLong(hospitalId));
                    lisRequestInfo.setPatientId(StringUtils.stringToLong(requestInfo.getPatientID()));
                    lisRequestInfo.setPatientNumber(requestInfo.getPatientNumber());
                    lisRequestInfo.setSampleNo(requestInfo.getHospSampleNumber());
                    lisRequestInfo.setSamplingDate(requestInfo.getSamplingDate());
                    lisRequestInfo.setTransFlag(GenerateConstant.num_0);
                    lisRequestInfo.setComments(JSON.toJSONString(requestInfo));

                    // 转换后的申请单信息
                    SpecimenCheckAndProjectDocumentIdsDTO documentIdsDTO = requestInfoMapping(requestInfo, sexTypeList,
                            ageTypeList, itemRelateList);

                    requestTestItemService.insertLisRequestInfo(lisRequestInfo, documentIdsDTO);
                }
            }

        }
    }

    /**
     *  同步检验结果数据
     */
    @Scheduled(cron = "0/5 * * * * ?")
    public void SynchroRequestTestResult(){
        WLisRequestQuery query = new WLisRequestQuery();
        query.setHospitalId(StringUtils.stringToLong(hospitalId));
        query.setTransFlag(0);
        List<WLisRequestInfo> lisRequestInfoList = requestTestItemService.queryLisRequestInfo(query);
        if(!CollectionUtils.isEmpty(lisRequestInfoList)){
            for(WLisRequestInfo requestInfo : lisRequestInfoList){
                if(checkSpecimenResult(requestInfo)){
                    WLisRequestQuery info = new WLisRequestQuery();
                    info.setHospitalId(StringUtils.stringToLong(hospitalId));
                    info.setBarCode(requestInfo.getBarCode());
                    requestTestItemService.updateLisRequestInfo(info);
                }
            }
        }

    }

    private SpecimenCheckAndProjectDocumentIdsDTO requestInfoMapping(XiCangRequestInfo requestInfo,
                                                                     List<GeneralDTO> sexTypeList,
                                                                     List<GeneralDTO> ageTypeList,
                                                                     List<HospitalProjectLink> itemRelateList){
        SpecimenCheckAndProjectDocumentIdsDTO documentIdsDTO = new SpecimenCheckAndProjectDocumentIdsDTO();
        // 开单项目编号
        for(HospitalProjectLink relate : itemRelateList){
            if(requestInfo.getItemCode().equals(relate.getHospitalDocumentId())){
                documentIdsDTO.setProjectDocumentIds(Arrays.asList(StringUtils.null2Str(relate.getProjectDocumentId())));
                break;
            }
        }
        documentIdsDTO.setPlaceholderCode(requestInfo.getHospSampleID());
        documentIdsDTO.setOutpatientId(requestInfo.getPatientNumber());
        documentIdsDTO.setPatientName(requestInfo.getName());
        // -- 0 女 1 男，2 未知
        for(GeneralDTO generalDTO : sexTypeList){
            if("0".equals(requestInfo.getSex()) && "1".equals(generalDTO.getTypeInfoCode())){
                documentIdsDTO.setPatientSex(generalDTO.getTypeInfoId());
                break;
            }else if("1".equals(requestInfo.getSex()) && "0".equals(generalDTO.getTypeInfoCode())){
                documentIdsDTO.setPatientSex(generalDTO.getTypeInfoId());
                break;
            }else if("kong".equals(generalDTO.getTypeInfoCode())){
                documentIdsDTO.setPatientSex(generalDTO.getTypeInfoId());
            }
        }
        documentIdsDTO.setPatientAge(StringUtils.stringToLong(requestInfo.getAge()));
        // 讨论一下，怎么判断
//                    documentIdsDTO.setPatientAgeType(requestInfo.getAgeUnit());
        for(GeneralDTO generalDTO : ageTypeList){
            if("岁".equals(generalDTO.getTypeInfoName())){
                documentIdsDTO.setPatientAgeType(generalDTO.getTypeInfoId());
                break;
            }
        }
        documentIdsDTO.setPatientId(requestInfo.getPatientID());
//                    documentIdsDTO.setPatientIdCardNum(requestInfo.get);
        documentIdsDTO.setBedNum(requestInfo.getBedNumber());
        documentIdsDTO.setHospitalId(StringUtils.stringToLong(hospitalId));
        // 讨论一下，怎么判断
        if("体检".equals(requestInfo.getPatientSource())){
                        documentIdsDTO.setPatientType(2);
        }else if("门诊".equals(requestInfo.getPatientSource())){
            documentIdsDTO.setPatientType(0);
        }else{
            documentIdsDTO.setPatientType(1);
        }
        // 标本类别是个什么东东
        documentIdsDTO.setSpecimenType(110);
        // 是个什么东东，申请科室
        documentIdsDTO.setApplicationDepartmentId(45L);
        documentIdsDTO.setApplicationDoctorId(5L);
        documentIdsDTO.setSamplingDate(DateUtil.format(requestInfo.getSamplingDate(), DateUtil.YYYMMDDHHMMMSS) );
        // 优先标志 (0: 普通; 1: 急诊; )
        documentIdsDTO.setPatientTag(0);
        documentIdsDTO.setDiagnosis(requestInfo.getDiagnostication());
        documentIdsDTO.setPatientTel(requestInfo.getPatientTel());
        documentIdsDTO.setRemarks(requestInfo.getRemark());

        return documentIdsDTO;
    }

    /**
     *  判断检验结果是否出来
     *
     * @param requestInfo
     */
    private boolean checkSpecimenResult(WLisRequestInfo requestInfo){
        SpecimenRegisterQuery registerQuery = new SpecimenRegisterQuery();
        registerQuery.setHospitalId(StringUtils.stringToLong(hospitalId));
        registerQuery.setPlaceholderCode(requestInfo.getBarCode());
        registerQuery.setStatus(1);
        registerQuery.setSpecimenStatusBig(StringUtils.charToByte('2'));

        boolean isHandler = false;
        List<SpecimenRegister> registerList = testItemSynchroService.querySpecimenRegister(registerQuery);
        if(!CollectionUtils.isEmpty(registerList)){
            isHandler = testResultXmlExport.generateXml(registerList);
            testResultXmlExport.generateReportImage(registerList);
        }

        return isHandler;
    }

    private List<HospitalProjectLink> getRequestItemInfo(){
        HospitalProjectLink itemRelate = new HospitalProjectLink();
        itemRelate.setObjectId(StringUtils.stringToLong(hospitalId));
        List<HospitalProjectLink> itemRelateList = requestTestItemService.queryRequestItemRelate(itemRelate);
        if(CollectionUtils.isEmpty(itemRelateList)){
            itemRelateList = Collections.emptyList();
        }

        return itemRelateList;
    }

}
